﻿using System.IO.Ports;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MG.Communication.ModBus;
using MG.Repository;
using MG.SmartHMI.Common;
using MG.SmartHMI.Entity.DAO;
using MG.SmartHMI.Model.VO;
using MG.Util.Data;
using MG.Util.Log;
using Nelibur.ObjectMapper;
using ModbusInfo = MG.SmartHMI.Entity.DAO.ModbusInfo;

namespace MG.SmartHMI.ViewModel
{
    public partial class ConfigViewModel : ObservableRecipient
    {
        [ObservableProperty]
        private ModbusInfVO modbusInfo;

        [ObservableProperty]
        private List<string> comResource;

        [ObservableProperty]
        private string appTitle;

        public ConfigViewModel()
        {
            Update2UI();
        }

        [RelayCommand]
        private void ScanCom()
        {
            ComResource = SerialPort.GetPortNames().ToList();
            if (ComResource == null || ComResource.Count() < 1) EventBus.Default.PopUpWarning("无可用通讯串口");
        }

        [RelayCommand]
        private void Save()
        {
            RepositoryService<ModbusInfo>.Instance.Update(TinyMapper.Map<ModbusInfo>(ModbusInfo));
            RepositoryService<Config>.Instance.UpdateFiled(t => new Config() { Value = AppTitle }, q => q.Key.Equals("AppTitle") && !q.IsDelete);

            Update2UI();
            EventBus.Default.PopUpSuccess("已保存");
            EventBus.Default.Log(new LogInfo($"保存设备参数"));
            EventBus.Default.Log(new LogInfo($"保存设备参数\r\n{ModbusInfo.ToJson().FormatJson()}\r\n", LogLevel.Trace));
        }

        [RelayCommand]
        private void ConnectTest()
        {
            var res = false;
            if (ModbusInfo.EnableRtu)
            {
                ModbusRtu rtu = new ModbusRtu();
                try
                {
                    rtu.SerialPortInni(sp =>
                    {
                        sp.PortName = ModbusInfo.PortName;
                        sp.BaudRate = ModbusInfo.BaudRate;
                        sp.DataBits = ModbusInfo.DataBits;
                        sp.StopBits = (StopBits)ModbusInfo.StopBits;
                        sp.Parity = (Parity)ModbusInfo.Parity;
                    });
                    rtu.Open();
                    res = rtu.IsOpen();
                }
                catch (Exception e1)
                {
                    MessageBox.Show($"连接失败\r\n{e1.Message}", "连接测试", MessageBoxButton.OK);
                }
                finally
                {
                    rtu?.Close();
                    rtu?.Dispose();
                }
            }
            else
            {
                ModbusTcpNet tcp = new ModbusTcpNet(ModbusInfo.IP, ModbusInfo.Port);

                try
                {
                    res = tcp.ConnectServer().IsSuccess;
                }
                catch (Exception e1)
                {
                    MessageBox.Show($"连接失败\r\n{e1.Message}", "连接测试", MessageBoxButton.OK);
                }
                finally
                {
                    tcp?.ConnectClose();
                    tcp?.Dispose();
                }

                if (res)
                    EventBus.Default.PopUpSuccess("连接成功");
                else
                    EventBus.Default.PopUpError("连接失败");
            }
        }

        private void Update2UI()
        {
            var modinfdao = RepositoryService<ModbusInfo>.Instance.Query(t => !t.IsDelete);
            if (modinfdao == null || modinfdao.Count() < 1)
            {
                RepositoryService<ModbusInfo>.Instance.Add(new ModbusInfo());
                modinfdao = RepositoryService<ModbusInfo>.Instance.Query(t => !t.IsDelete);
            }
            ModbusInfo = TinyMapper.Map<ModbusInfVO>(modinfdao.First());

            var cfgdao = RepositoryService<Config>.Instance.Query(t => t.Key.Equals("AppTitle") && !t.IsDelete);
            if (cfgdao == null || cfgdao.Count() < 1)
            {
                RepositoryService<Config>.Instance.Add(new Config() { Key = "AppTitle", Value = "" });
                cfgdao = RepositoryService<Config>.Instance.Query(t => t.Key.Equals("AppTitle") && !t.IsDelete);
            }
            AppTitle = cfgdao.First().Value;
        }
    }
}